﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace WPFDemoMVVM.Helpers
{
    public class MultiSelectorHelper
    {
        

        #region Bindable SelectedItems
        public static IList GetBindableSelectedItems(DependencyObject obj)
        {
            return (IList)obj.GetValue(BindableSelectedItemsProperty);
        }

        public static void SetBindableSelectedItems(DependencyObject obj,IList value)
        {
            obj.SetValue(BindableSelectedItemsProperty, value);
        }

        public static readonly DependencyProperty BindableSelectedItemsProperty = DependencyProperty.RegisterAttached(
            "BindableSelectedItems",
            typeof(IList),
            typeof(MultiSelectorHelper),
            new PropertyMetadata(null)
            );
        #endregion


        #region Monitor SelectionChanged

        public static bool GetMonitorSelectionChanged(DependencyObject obj)
        {
            return (bool)obj.GetValue(MonitorSelectionChangedProperty);
        }

        public static void SetMonitorSelectionChanged(DependencyObject obj, bool value)
        {
            obj.SetValue(MonitorSelectionChangedProperty, value);
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MonitorSelectionChangedProperty =
            DependencyProperty.RegisterAttached("MonitorSelectionChanged", typeof(bool), 
                typeof(MultiSelectorHelper), new PropertyMetadata(false, MonitorSelectionChangedPropertyCallBack));

        private static void MonitorSelectionChangedPropertyCallBack(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is not MultiSelector selector)
                throw new InvalidOperationException();

            if ((bool)e.NewValue)
                selector.SelectionChanged += OnSelectionChanged;
            else
                selector.SelectionChanged -= OnSelectionChanged;

        }

        private static void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selector = (MultiSelector)sender;
            SetBindableSelectedItems(selector,selector.SelectedItems);
            selector.GetBindingExpression(BindableSelectedItemsProperty).UpdateSource();
        }



        #endregion


    }
}
